package org.jeecg.modules.livemanager;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.LiveAPIConfig;
import org.jeecg.config.LiveConfig;
import org.jeecg.modules.live.entity.LiveComment;
import org.jeecg.modules.live.entity.LiveEstoppel;
import org.jeecg.modules.live.entity.LiveInfo;
import org.jeecg.modules.live.entity.LiveLikes;
import org.jeecg.modules.live.service.ILiveCommentService;
import org.jeecg.modules.live.service.ILiveEstoppelService;
import org.jeecg.modules.live.service.ILiveInfoService;
import org.jeecg.modules.live.service.ILiveLikesService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.util.CommonUtil;
import org.jeecg.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 直播信息
 * @Author: jeecg-boot
 * @Date: 2020-05-06
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "直播管理")
@RestController
@RequestMapping("/liveManage/liveInfo")
public class LiveManageController extends JeecgController<LiveInfo, ILiveInfoService> {
    @Autowired
    private ILiveInfoService liveInfoService;
    @Autowired
    private ILiveLikesService liveLikesService;
    @Autowired
    private LiveAPIConfig liveAPIConfig;
    @Autowired
    private LiveConfig liveConfig;
    @Autowired
    private ILiveCommentService liveCommentService;
    @Autowired
    private ILiveEstoppelService liveEstoppelService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页列表查询 - 根据直播状态查询列表
     *
     * @param liveInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "直播管理信息-分页列表查询")
    @ApiOperation(value = "直播管理信息-分页列表查询", notes = "直播管理信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(LiveInfo liveInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        // 根据当前时间判断更改直播状态
        List<LiveInfo> liveInfoList = updateLiveInfoByTime();
        //批量更改直播状态
        if(null !=liveInfoList && liveInfoList.size() >0){
            if(!liveInfoService.updateBatchById(liveInfoList)){
                return Result.error("批量更改直播状态 失败！");
            }
        }
        Result<IPage<LiveInfo>> result = new Result<IPage<LiveInfo>>();
        String liveStatus = req.getParameter("liveStatus");// 直播状态 0：直播中 1：直播未开始 2：直播结束 3：直播强制终止
        QueryWrapper<LiveInfo> queryWrapper = QueryGenerator.initQueryWrapper(liveInfo, req.getParameterMap());
        Page<LiveInfo> page = new Page<LiveInfo>(pageNo, pageSize);
        if ("0".equals(liveStatus)) {
            queryWrapper.eq("live_status", "0");//查询状态：直播中
        } else {
            queryWrapper.in("live_status", "2", "3");//查询状态：直播结束 终止
        }
        IPage<LiveInfo> pageList = liveInfoService.page(page, queryWrapper);
        List<LiveInfo> records = pageList.getRecords();
        records.forEach(item->{
            //获取用户 设置昵称 头像
            SysUser sysUser = sysUserService.getById(item.getUserId());
            if(null != sysUser){
                item.setUserNickName(sysUser.getUsername());
                item.setUserHeadPhoto(sysUser.getAvatar());
            }else{
                item.setUserNickName("");
                item.setUserHeadPhoto("");
            }
        });
        result.setSuccess(true);
        result.setResult(pageList);
        return result;

    }


    /**
     * 更改直播信息表直播状态 根据当前时间 判断更改直播状态
     *
     * @param
     * @return
     */
//    @AutoLog(value = "更改直播信息表直播状态-根据当前时间判断更改直播状态")
//    @ApiOperation(value = "更改直播信息表直播状态", notes = "更改直播信息表直播状态-根据当前时间判断更改直播状态")
//    @GetMapping(value = "/updateLiveInfoByTime")
    public List<LiveInfo> updateLiveInfoByTime() {

        List<LiveInfo> liveInfoList = liveInfoService.list();
        if (null == liveInfoList || liveInfoList.size() <= 0) {
            return null;
        }
        List<LiveInfo> liveInfoListTo = new ArrayList<>();
        for (LiveInfo liveInfo : liveInfoList) {
            long startTime = liveInfo.getLiveStartTime().getTime();
            long endTime = liveInfo.getLiveEndTime().getTime();
            long nowTime = DateUtils.getDate().getTime();
            // 设置状态 直播状态 0：直播中 1：直播未开始 2：直播结束 3：直播强制终止
            if (3 == liveInfo.getLiveStatus()) {
                continue;
            }
            if (2 == liveInfo.getLiveStatus()) {
                continue;
            }
            if (nowTime < startTime) {
                if (1 == liveInfo.getLiveStatus()) {
                    continue;
                }
                liveInfo.setLiveStatus(1);
            }
            if (nowTime >= startTime && nowTime < endTime) {
                if (0 == liveInfo.getLiveStatus()) {
                    continue;
                }
                liveInfo.setLiveStatus(0);
            }
            liveInfoListTo.add(liveInfo);
        }
        return liveInfoListTo;
    }


    /**
     * 直播流管理相关接口 > 断开直播流
     *
     * @param
     * @return
     */
    @AutoLog(value = "断开直播流")
    @ApiOperation(value = "断开直播流", notes = "断开直播流-调云API断开直播流,参数必填 id，streamId")
    @GetMapping(value = "/updateDisconnectLiveStream")
    public Result<?> updateDisconnectLiveStream(@RequestBody LiveInfo liveInfo) {

        if (null == liveInfo || StringUtils.isEmpty(liveInfo.getStreamId())) {
            Result.error("liveInfo 或 streamId 参数为空！");
        }
        String resp;
        try {
            //断开直播流 url  domainName 加速域名
            String disconnectLiveStreamUrl = CommonUtil.disconnectLiveStream(liveAPIConfig.getDropLiveStreamAction(), liveConfig.getSecretId(),
                    "2018-08-01", liveConfig.getPushDomainName(), liveConfig.getAppName(),
                    liveInfo.getStreamId(), "GET", liveAPIConfig.getRequestDomainName(), liveConfig.getSecretKey());

            //开始请求 断开直播流
            resp = com.xinke.common.util.HttpClientUtil.sendGetData(disconnectLiveStreamUrl, "utf-8");
            Map map = (Map) JSONObject.parse(resp);
            if (map.isEmpty() || null == map) {
                return Result.error("断开直播流异常,返回空！");
            }
            // 获取 输出参数 ：唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
            Map map1 = (Map) JSONObject.parse(map.get("Response").toString());
            String requestIdY = map1.get("RequestId").toString();
            LiveInfo liveInfo1 = liveInfoService.getById(liveInfo.getId());
            //更新直播终止状态
            if(null != liveInfo1){
                liveInfo1.setLiveStatus(3);
                liveInfoService.updateById(liveInfo1);
            }
            return Result.ok(map1);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("断开直播流失败，异常！");
            //签名失败 根据实际情况，存在以下签名失败的错误码，请根据实际情况处理。
            // 错误代码	错误描述
            //AuthFailure.SignatureExpire	签名过期
            //AuthFailure.SecretIdNotFound	密钥不存在
            //AuthFailure.SignatureFailure	签名错误
            //AuthFailure.TokenFailure	token 错误
            //AuthFailure.InvalidSecretId	密钥非法（不是云 API 密钥类型）
        }

    }


    /**
     * 直播流管理相关接口  > 禁推直播流
     *
     * @param
     * @return
     */
    @AutoLog(value = "禁推直播流")
    @ApiOperation(value = "禁推直播流", notes = "禁推直播流-参数必填 id, streamId")
    @PostMapping(value = "/forbidLiveStream")
    public Result<?> forbidLiveStream(
            @RequestParam(name="id",required=true) String id,
            @RequestParam(name="streamId",required=true) String streamId) {

        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(streamId)) {
            Result.error("id 或 streamId 参数为空！");
        }
        String resp;
        try {
            LiveInfo liveInfo1 = liveInfoService.getById(id);
            //获取当前用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            //更新直播终止状态
            if(null != liveInfo1){
                if(null != sysUser){
                    liveInfo1.setUpdateBy(sysUser.getUsername());//修改人
                }
                liveInfo1.setUpdateTime(new Date());//修改时间
                liveInfo1.setLiveStatus(3);
                if(!liveInfoService.updateById(liveInfo1)){
                    return Result.error("取消直播权限失败，数据库设置直播状态失败！");
                }
            }
            //禁推直播流 url
            String forbidLiveStreamUrl = CommonUtil.forbidLiveStream(liveAPIConfig.getForbidLiveStreamAction(), liveConfig.getSecretId(),
                    "2018-08-01", liveConfig.getPushDomainName(), liveConfig.getAppName(),
                    streamId, "GET", liveAPIConfig.getRequestDomainName(), liveConfig.getSecretKey());
            //开始请求 禁推直播流
            resp = com.xinke.common.util.HttpClientUtil.sendGetData(forbidLiveStreamUrl, "utf-8");
            Map map = (Map) JSONObject.parse(resp);
            if (map.isEmpty() || null == map) {
                return Result.error("禁推直播流异常,返回空！");
            }
            // 获取 输出参数 ：唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
            Map map1 = (Map) JSONObject.parse(map.get("Response").toString());
            String requestIdY = map1.get("RequestId").toString();
            return Result.ok(map1);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("禁推直播流失败，异常！");
            //签名失败 根据实际情况，存在以下签名失败的错误码，请根据实际情况处理。
            // 错误代码	错误描述
            //AuthFailure.SignatureExpire	签名过期
            //AuthFailure.SecretIdNotFound	密钥不存在
            //AuthFailure.SignatureFailure	签名错误
            //AuthFailure.TokenFailure	token 错误
            //AuthFailure.InvalidSecretId	密钥非法（不是云 API 密钥类型）
        }

    }


    /**
     * 直播流管理相关接口 > 恢复直播推流
     *
     * @param streamId
     * @return
     */
    @AutoLog(value = "恢复直播推流")
    @ApiOperation(value="恢复直播推流", notes="恢复直播推流.参数 streamId")
    @GetMapping(value = "/resumeLiveStreaming")
    public Result<?> resumeLiveStreaming(@RequestParam(name="streamId",required=true) String streamId) {
        if (StringUtils.isEmpty(streamId)) {
            return Result.error("参数 streamId 为空！");
        }
        String resp;
        Map<String, Object> resultMap = new HashMap();
        try {
            //恢复直播推流
            String queryResumeLiveStreamingUrl = CommonUtil.resumeLiveStreaming(liveAPIConfig.getResumeLiveStreamAction(), liveConfig.getSecretId(),
                    "2018-08-01",  liveConfig.getPushDomainName(), streamId,
                    liveConfig.getAppName(), "GET", liveAPIConfig.getRequestDomainName(), liveConfig.getSecretKey());

            //开始请求 恢复直播推流
            resp = com.xinke.common.util.HttpClientUtil.sendGetDataByContentType(queryResumeLiveStreamingUrl, "utf-8","application/x-www-form-urlencoded");
            Map map = (Map) JSONObject.parse(resp);
            if (map.isEmpty() || null == map) {
                return Result.error("恢复直播推流 失败！");
            }
            // 获取 输出参数 ：唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
            Map map1 = (Map) JSONObject.parse(map.get("Response").toString());
            String requestIdY = map1.get("RequestId").toString();

            return Result.ok(map1);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("恢复直播推流，异常！");
            //签名失败 根据实际情况，存在以下签名失败的错误码，请根据实际情况处理。
            // 错误代码	错误描述
            //AuthFailure.SignatureExpire	签名过期
            //AuthFailure.SecretIdNotFound	密钥不存在
            //AuthFailure.SignatureFailure	签名错误
            //AuthFailure.TokenFailure	token 错误
            //AuthFailure.InvalidSecretId	密钥非法（不是云 API 密钥类型）
        }

    }


    /**
     * 通过 idList 查询点赞数量
     *
     * @param idList
     * @return
     */
    @AutoLog(value = "直播点赞-通过idList查询")
    @ApiOperation(value = "直播点赞-通过idList查询", notes = "直播点赞-通过idList查询")
    @GetMapping(value = "/queryByIdList")
    public Result<?> queryByIdList(@RequestParam(name = "idList", required = true) String idList) {

        Result<List<LiveLikes>> result = new Result<>();
        QueryWrapper<LiveLikes> queryWrapper = new QueryWrapper<LiveLikes>();
        queryWrapper.in("live_id", idList);
        List<LiveLikes> liveLikes = liveLikesService.list(queryWrapper);
        result.setResult(liveLikes);
        result.setSuccess(true);
        return result;
    }

    /**
     * 直播管理 直播评论 根据直播ID 分页列表查询
     *
     * @param liveComment
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "根据直播ID分页查直播评论")
    @ApiOperation(value = "根据直播ID分页查直播评论", notes = "根据直播ID分页查直播评论-参数liveId")
    @GetMapping(value = "/liveCommentlist")
    public Result<?> queryLiveCommentPageList(LiveComment liveComment,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                              HttpServletRequest req) {
        Result<IPage<LiveComment>> result = new Result<IPage<LiveComment>>();
        String liveId = req.getParameter("liveId");// 直播Id

        QueryWrapper<LiveComment> queryWrapper = QueryGenerator.initQueryWrapper(liveComment, req.getParameterMap());
        Page<LiveComment> page = new Page<LiveComment>(pageNo, pageSize);
        queryWrapper.eq("live_id", liveId);//根据直播ID查询 直播评论
        queryWrapper.eq("sensitive_words", 0);//根是否敏感词：0 不是 1 是
        queryWrapper.orderByDesc("create_time");//根据创建时间 正序
        IPage<LiveComment> pageList = liveCommentService.page(page, queryWrapper);

        List<LiveComment> records = pageList.getRecords();
        //设置评论是否被禁言
        records.forEach(item->{
            QueryWrapper<LiveEstoppel> queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("user_id", item.getCommentUserId());
            List<LiveEstoppel> list = liveEstoppelService.list(queryWrapper1);
            if(null != list && list.size() > 0){
                LiveEstoppel estoppel = list.get(0);
                item.setLiveEstoppel(estoppel.getEstoppelFlag());
            }else{
                item.setLiveEstoppel(2);
            }
        });
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 直播管理 直播评论 根据直播ID查询总评论数 count
     *
     * @param id
     * @return
     */
    @AutoLog(value = "根据直播ID查询总评论数")
    @ApiOperation(value = "根据直播ID查询总评论数", notes = "根据直播ID查询总评论数")
    @GetMapping(value = "/queryLiveCommentByIdCount")
    public Result<?> queryLiveCommentByIdCount(@RequestParam(name = "id", required = true) String id) {

        if (StringUtils.isEmpty(id)) {
            return Result.error("参数id为空！");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("live_id", id);
        int count = liveCommentService.count(queryWrapper);
        return Result.ok(count);

    }


    /**
     * 直播管理 直播禁言-分页列表查询
     *
     * @param liveEstoppel
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "直播禁言-分页列表查询")
    @ApiOperation(value="直播禁言-分页列表查询", notes="直播禁言-分页列表查询")
    @GetMapping(value = "/queryEstoppelPageList")
    public Result<?> queryEstoppelPageList(LiveEstoppel liveEstoppel,
                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                           HttpServletRequest req) {
        QueryWrapper<LiveEstoppel> queryWrapper = QueryGenerator.initQueryWrapper(liveEstoppel, req.getParameterMap());
        Page<LiveEstoppel> page = new Page<LiveEstoppel>(pageNo, pageSize);
        IPage<LiveEstoppel> pageList = liveEstoppelService.page(page, queryWrapper);
        return Result.ok(pageList);
    }


    /**
     * 直播管理 禁言 根据用户ID禁言
     *
     * @param id
     * @return
     */
    @AutoLog(value = "直播禁言-根据用户评论人ID禁言")
    @ApiOperation(value = "直播禁言-根据用户评论人ID禁言", notes = "直播禁言-根据用户评论人ID禁言")
    @GetMapping(value = "/updateLiveEstoppel")
    public Result<?> updateLiveEstoppelById(@RequestParam(name = "id", required = true) String id) {

        if (StringUtils.isEmpty(id)) {
            return Result.error("参数id为空！");
        }
        //获取当前用户
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        if(null == sysUser){
//            return Result.error("获取当前用户失败！");
//        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", id);
        List<LiveEstoppel> list = liveEstoppelService.list(queryWrapper);
        if(null != list && list.size() > 0 && 1 ==  list.get(0).getEstoppelFlag()){
            return Result.ok("用户已禁言！");
        }else if(null != list && list.size() > 0 && 2 ==  list.get(0).getEstoppelFlag()){
            LiveEstoppel liveEstoppel = list.get(0);
            liveEstoppel.setUserId(id);
            liveEstoppel.setEstoppelFlag(1);// 直播禁言: (1-禁言,2-未禁言)
            if (liveEstoppelService.updateById(liveEstoppel)) {
                return Result.ok("禁言成功！");
            }
            return Result.error("禁言失败！");
        }
        LiveEstoppel liveEstoppel2 = new LiveEstoppel();
        liveEstoppel2.setUserId(id);
        liveEstoppel2.setEstoppelFlag(1);// 直播禁言: (1-禁言,2-未禁言)
        if (!liveEstoppelService.save(liveEstoppel2)) {
            return Result.error("禁言失败！");
        }
        return Result.ok("禁言成功！");
    }

    /**
     * 直播管理  根据用户ID解除禁言
     *
     * @param id
     * @return
     */
    @AutoLog(value = "直播解除禁言-根据用户ID解除禁言")
    @ApiOperation(value = "直播解除禁言-根据用户ID解除禁言", notes = "直播解除禁言-根据用户ID解除禁言")
    @PostMapping(value = "/updateRelieveEstoppelById")
    public Result<?> updateRelieveEstoppelById(@RequestParam(name = "id", required = true) String id) {

        if (StringUtils.isEmpty(id)) {
            return Result.error("参数id为空！");
        }
        //获取当前用户
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        if(null == sysUser){
//            return Result.error("获取当前用户失败！");
//        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", id);
        List<LiveEstoppel> list = liveEstoppelService.list(queryWrapper);
        if(null != list && list.size() > 0 && 2 == list.get(0).getEstoppelFlag()){
            return Result.ok("用户已解除禁言！");
        }else if(null != list && list.size() > 0 && 1 == list.get(0).getEstoppelFlag()){
            LiveEstoppel liveEstoppel = list.get(0);
            liveEstoppel.setUserId(id);
            liveEstoppel.setEstoppelFlag(2);// 直播禁言: (1-禁言,2-未禁言)
            if (!liveEstoppelService.updateById(liveEstoppel)) {
                return Result.error("解除禁言失败！");
            }
            return Result.ok("解除禁言成功！");
        }
        return Result.ok("用户已解除禁言！");
    }


    /**
     * 统计查询相关接口 查询流的播放信息
     *
     * @param streamId
     * @return
     */
    @AutoLog(value = "查询流的播放信息列表-获取在线人数")
    @ApiOperation(value = "查询流的播放信息列表-获取在线人数", notes = "查询流的播放信息列表-获取在线人数,参数 streamId")
    @GetMapping(value = "/queryLiveDetailsById")
    public Result<?> queryLiveDetailsById(@RequestParam(name = "streamId", required = true) String streamId) {

        Map<String, Object> resultMap = new HashMap();
        Result<?> result = new Result<>();
        if (StringUtils.isEmpty(streamId)) {
            Result.error("参数 streamId 为空！");
        }
        result = getPlayInfo(streamId);
        return result;

    }

    /**
     * 统计查询相关接口 查询流的播放信息
     *
     * @param streamId
     * @return
     */
    public Result<?> getPlayInfo(String streamId) {
        if (StringUtils.isEmpty(streamId)) {
            return Result.error("参数 streamId 为空！");
        }
        long startTime3 = System.currentTimeMillis() - 3 * 60 * 1000;//获取当前时间减3分钟之后的时间
        String startTime = DateUtils.date2Str(new Date(startTime3), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        long currentTime = System.currentTimeMillis() + 30 * 60 * 1000;//获取当前时间加半小时之后的时间
        Date date = new Date(currentTime);
        String endTime = DateUtils.date2Str(date, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        String resp;
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("Online",0);
        try {
            //查询流的播放信息 url
            String queryLiveDetailsByIdUrl = CommonUtil.queryStreamPlayInfoList(liveAPIConfig.getDescribeStreamPlayInfoListAction(), liveConfig.getSecretId(),
                    "2018-08-01", startTime, endTime, liveConfig.getBroadcastDomainName(), streamId,
                    null, "GET", liveAPIConfig.getRequestDomainName(), liveConfig.getSecretKey());
            log.info("queryLiveDetailsByIdUrl:{}",queryLiveDetailsByIdUrl);
            //开始请求 查询流的播放信息
            resp = com.xinke.common.util.HttpClientUtil.sendGetDataByContentType(queryLiveDetailsByIdUrl, "utf-8","application/json");
            log.info("resp:{}",resp);
            Map map = (Map) JSONObject.parse(resp);
            if (map.isEmpty() || null == map) {
                return Result.ok(resultMap);
            }

            Map map1 = (Map) JSONObject.parse(map.get("Response").toString());
            String requestIdY = map1.get("RequestId").toString();// 获取 输出参数 ：唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。

            List dataInfoList = (List) JSONObject.parse(map1.get("DataInfoList").toString());
            if(!dataInfoList.isEmpty()){
                String onlineY = "0";
                String timeY = "";
                if(dataInfoList.size() > 1){// 腾讯云在线人数接口有延迟2分钟多一点 所以取当前时间减2分钟之后的在线人数
                    Map map2 = (Map) JSONObject.parse(dataInfoList.get(1).toString());
                    timeY = map2.get("Time").toString(); //数据时间点，格式：yyyy-mm-dd HH:MM:SS。
                    onlineY = map2.get("Online").toString(); // 在线人数。
                }
                if(onlineY.equals("0")){
                    Map map3 = (Map) JSONObject.parse(dataInfoList.get(0).toString());
                    timeY = map3.get("Time").toString(); //数据时间点，格式：yyyy-mm-dd HH:MM:SS。
                    onlineY = map3.get("Online").toString(); // 在线人数。
                }
                resultMap.put("Online", onlineY);
                resultMap.put("Time", timeY);

            }
        } catch (Exception e) {
            log.error("",e);
//             return Result.error("查询流的播放信息异常失败，异常！");
            //签名失败 根据实际情况，存在以下签名失败的错误码，请根据实际情况处理。
            // 错误代码	错误描述
            //AuthFailure.SignatureExpire	签名过期
            //AuthFailure.SecretIdNotFound	密钥不存在
            //AuthFailure.SignatureFailure	签名错误
            //AuthFailure.TokenFailure	token 错误
            //AuthFailure.InvalidSecretId	密钥非法（不是云 API 密钥类型）
        }
        return Result.ok(resultMap);

    }


    /**
     * 返回时时在直播的列表
     *
     * @param
     * @return
     */
    @AutoLog(value = "直播的列表-返回时时在直播的列表")
    @ApiOperation(value = "直播的列表-返回时时在直播的列表", notes = "直播的列表-返回时时在直播的列表")
    @PostMapping(value = "/queryQueryPlaylistStreamList")
    public Result<?> queryQueryPlaylistStreamList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {

        Result<IPage<LiveInfo>> result = new Result<>();
        Map<String,Object> mapNull = new HashMap<String,Object>();
        Page<LiveInfo> page = new Page<LiveInfo>(pageNo, pageSize);

        Result<?> playingStreamResult = getPlayingStream(pageNo,pageSize);
        if(500 == playingStreamResult.getCode()){
            return Result.ok(mapNull);
        }
        List<Map<String, Object>> resultMapList = (List)playingStreamResult.getResult();
        StringBuffer streamNameId=new StringBuffer();
        for (Map list :resultMapList) {
            streamNameId.append(list.get("streamNameY").toString())
                    .append(",");
        }

        String streamNameIds = streamNameId.toString();
        if(!StringUtils.isEmpty(streamNameIds)){
            streamNameIds = streamNameIds.substring(0,streamNameIds.length()-1);
        }else{
            return Result.ok(mapNull);
        }
        QueryWrapper<LiveInfo> queryWrapper = new QueryWrapper<LiveInfo>();

        queryWrapper.in("stream_id", streamNameIds.split(","));
        queryWrapper.orderByDesc("update_time");
        IPage<LiveInfo> pageList = liveInfoService.page(page, queryWrapper);
        List<LiveInfo> records = pageList.getRecords();
        records.forEach(item->{
            //获取用户 设置昵称 头像
            SysUser sysUser = sysUserService.getById(item.getUserId());
            if(null != sysUser){
                item.setUserNickName(sysUser.getUsername());
                item.setUserHeadPhoto(sysUser.getAvatar());
            }else{
                item.setUserNickName("");
                item.setUserHeadPhoto("");
            }
        });
        result.setSuccess(true);
        result.setResult(pageList);
        result.setCode(200);
        return result;//返回时时在直播的列表
    }


    /**
     * 直播流管理相关接口 查询直播中的流
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Result<?> getPlayingStream(Integer pageNo, Integer pageSize) {
        if (null == pageNo || null == pageSize) {
            Result.error("pageNo或pageSize参数为空！");
        }

        String resp;
        List<Map<String, Object>> resultMapList = new ArrayList<>();

        try {
            String streamsLiveUrl = CommonUtil.queryingStreamsLive(liveAPIConfig.getLiveStreamOnlineListAction(), liveConfig.getSecretId(),
                    "2018-08-01", liveConfig.getPushDomainName(), liveConfig.getAppName(), pageNo, pageSize,
                    null, "GET", liveAPIConfig.getRequestDomainName(), liveConfig.getSecretKey());

            //开始请求 查询直播中的流
            resp = com.xinke.common.util.HttpClientUtil.sendGetData(streamsLiveUrl, "utf-8");
            Map map = (Map) JSONObject.parse(resp);
            if (map.isEmpty() || null == map) {
                return Result.error("查询直播中的流异常,返回空！");
            }
            Map map1 = (Map) JSONObject.parse(map.get("Response").toString());

            if(!map1.isEmpty() && null != map1){
                String totalNumY = map1.get("TotalNum").toString();
                String totalPageY = map1.get("TotalPage").toString();
                String pageNumY = map1.get("PageNum").toString();
                String pageSizeY = map1.get("PageSize").toString();
                String requestIdY = map1.get("RequestId").toString();
                List onlineInfoList = (List) JSONObject.parse(map1.get("OnlineInfo").toString());
                for (Object list:onlineInfoList) {
                    Map<String, Object> resultMap = new HashMap();
                    resultMap.put("totalNumY", totalNumY);
                    resultMap.put("totalPageY", totalPageY);
                    resultMap.put("pageNumY", pageNumY);
                    resultMap.put("pageSizeY", pageSizeY);
                    resultMap.put("requestIdY", requestIdY);
                    Map map2 = (Map) JSONObject.parse(list.toString());
                    resultMap.put("streamNameY", map2.get("StreamName").toString()); //流名称 唯一， 确定app数据库哪一个用户
                    resultMap.put("appNameY", map2.get("AppName").toString());
                    resultMap.put("domainNameY", map2.get("DomainName").toString());
                    List publishTimeListList = (List) JSONObject.parse(map2.get("PublishTimeList").toString());
                    Map map3 = (Map) JSONObject.parse(publishTimeListList.get(0).toString());
                    resultMap.put("publishTimeY", map3.get("PublishTime").toString());
                    resultMapList.add(resultMap);
                }
            }
            return Result.ok(resultMapList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询直播中的流失败，异常！");
            //签名失败 根据实际情况，存在以下签名失败的错误码，请根据实际情况处理。
            // 错误代码	错误描述
            //AuthFailure.SignatureExpire	签名过期
            //AuthFailure.SecretIdNotFound	密钥不存在
            //AuthFailure.SignatureFailure	签名错误
            //AuthFailure.TokenFailure	token 错误
            //AuthFailure.InvalidSecretId	密钥非法（不是云 API 密钥类型）
        }

    }


//    public static void main(String[] args) {
//        String resp = "{\n" +
//                "  \"Response\": {\n" +
//                "    \"OnlineInfo\": [\n" +
//                "      {\n" +
//                "        \"StreamName\": \"5000_abcdefg\",\n" +
//                "        \"AppName\": \"live\",\n" +
//                "        \"DomainName\": \"5000.livepush.myqcloud.com\",\n" +
//                "        \"PublishTimeList\": [\n" +
//                "          {\n" +
//                "            \"PublishTime\": \"2017-10-24T12:00:00Z\"\n" +
//                "          }\n" +
//                "        ]\n" +
//                "      }\n" +
//                "    ],\n" +
//                "    \"TotalNum\": 1,\n" +
//                "    \"TotalPage\": 1,\n" +
//                "    \"PageNum\": 1,\n" +
//                "    \"PageSize\": 10,\n" +
//                "    \"RequestId\": \"8e50cdb5-56dc-408b-89b0-31818958d424\"\n" +
//                "  }\n" +
//                "}";
//        Map map = (Map) JSONObject.parse(resp);
//        Map map1 = (Map) JSONObject.parse(map.get("Response").toString());
//
//        String totalNumY = map1.get("TotalNum").toString();
//        String totalPageY = map1.get("TotalPage").toString();
//        String pageNumY = map1.get("PageNum").toString();
//        String pageSizeY = map1.get("PageSize").toString();
//        String requestIdY = map1.get("RequestId").toString();
//
//        List onlineInfoList = (List) JSONObject.parse(map1.get("OnlineInfo").toString());
//        Map map2 = (Map) JSONObject.parse(onlineInfoList.get(0).toString());
//        String streamNameY = map2.get("StreamName").toString(); //流名称 唯一， 确定app数据库哪一个用户
//        String appNameY = map2.get("AppName").toString(); //流名称 唯一， 确定app数据库哪一个用户
//        String domainNameY = map2.get("DomainName").toString(); //流名称 唯一， 确定app数据库哪一个用户
//
//        List publishTimeListList = (List) JSONObject.parse(map2.get("PublishTimeList").toString()); //流名称 唯一， 确定app数据库哪一个用户
//        Map map3 = (Map) JSONObject.parse(publishTimeListList.get(0).toString());
//        String publishTimeY = map3.get("PublishTime").toString(); //流名称 唯一， 确定app数据库哪一个用户
//        System.out.println(publishTimeY);
//    }

//    /**
//     * 查询某个时间点所有流的下行播放数据
//     * @param id
//     * @return
//     */
//    public Result<?> getAllStreamsDataPointTime(String queryTime){
//        if(StringUtils.isEmpty(queryTime)){
//            Result.error("queryTime参数为空！");
//        }
////        LiveInfo liveInfo = liveInfoService.getById(id);
////        String startTime = DateUtils.date2Str(liveInfo.getLiveStartTime(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
////        String endTime = DateUtils.date2Str(liveInfo.getLiveEndTime(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//
//        String resp;
//        Map<String,Object> resultMap = new HashMap();
//        try{
//            //查询某个时间点所有流的下行播放数据 url
//            String queryAllStreamsDataPointTimeUrl = CommonUtil.queryAllStreamsDataPointTime("DescribeAllStreamPlayInfoList",liveConfig.getSecretId(),
//                    "2018-08-01",queryTime,
//                    liveConfig.getAppName(),"GET",liveAPIConfig.getRequestDomainName(),liveConfig.getSecretKey());
//
//            //开始请求 查询某个时间点所有流的下行播放数据
//            resp = HttpClientUtil.sendGetData(queryAllStreamsDataPointTimeUrl,"utf-8");
//            Map map = (Map) JSONObject.parse(resp);
//            if(map.isEmpty() || null == map){
//                return Result.error("查询流的播放信息异常,返回空！");
//            }
//            // 获取 输出参数 ：唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
//            Map map1 = (Map) JSONObject.parse(map.get("Response").toString());
//            String requestIdY =map1.get("RequestId").toString();
//            String queryTimeY =map1.get("QueryTime").toString();
//
//            Map map2 = (Map) JSONObject.parse(map1.get("DataInfoList").toString());
//            List<String> dataInfoList = new ArrayList<>();
//            dataInfoList = (List) JSONObject.parse(map2.get("DataInfoList").toString());
//            String time;
//            String request = "0";//请求数
//            String online = "0";//在线人数
//            List<Map> resultList = new ArrayList<>();
//            for (String str : dataInfoList) {
//                Map map3 = (Map) JSONObject.parse(str.toString());
//                request =map1.get("Request").toString();
//                online =map1.get("Online").toString();
//            }
//            resultMap.put("requestId",requestIdY);//唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
//            resultMap.put("request",request);//请求数
//            resultMap.put("online",online);//在线人数
//            return Result.ok(resultMap);
//
//        }catch (Exception e){
//            e.printStackTrace();
//            return Result.error("查询流的播放信息异常失败，异常！");
//            //签名失败 根据实际情况，存在以下签名失败的错误码，请根据实际情况处理。
//            // 错误代码	错误描述
//            //AuthFailure.SignatureExpire	签名过期
//            //AuthFailure.SecretIdNotFound	密钥不存在
//            //AuthFailure.SignatureFailure	签名错误
//            //AuthFailure.TokenFailure	token 错误
//            //AuthFailure.InvalidSecretId	密钥非法（不是云 API 密钥类型）
//        }
//
//    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "直播信息-通过id删除")
//    @ApiOperation(value = "直播信息-通过id删除", notes = "直播信息-通过id删除")
//    @DeleteMapping(value = "/delete")
//    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
//        liveInfoService.removeById(id);
//        return Result.ok("删除成功!");
//    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
//    @AutoLog(value = "直播信息-批量删除")
//    @ApiOperation(value = "直播信息-批量删除", notes = "直播信息-批量删除")
//    @DeleteMapping(value = "/deleteBatch")
//    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        this.liveInfoService.removeByIds(Arrays.asList(ids.split(",")));
//        return Result.ok("批量删除成功！");
//    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "直播信息-通过id查询")
    @ApiOperation(value = "直播信息-通过id查询", notes = "直播信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        if(StringUtils.isEmpty(id)){
            return Result.error("参数 id 是空！");
        }
        LiveInfo liveInfo = liveInfoService.getById(id);
        if(null == liveInfo){
            return Result.error("没有直播信息 查询失败！");
        }
        //获取用户 设置昵称 头像
        SysUser sysUser = sysUserService.getById(liveInfo.getUserId());
        if(null != sysUser){
            liveInfo.setUserNickName(sysUser.getUsername());
            liveInfo.setUserHeadPhoto(sysUser.getAvatar());
        }else{
            liveInfo.setUserNickName("");
            liveInfo.setUserHeadPhoto("");
        }
        return Result.ok(liveInfo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param liveInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LiveInfo liveInfo) {
        return super.exportXls(request, liveInfo, LiveInfo.class, "直播信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LiveInfo.class);
    }

}
